<template>
  <div @contextmenu="showContextMenu" @contextmenu.prevent="blankMenu" style="min-width: 400px">
    <!-- 自定义右键-->
    <context-menu
      :show="contextMenuVisible"
      :offset="contextMenuOffset"
      @update:show="show => (contextMenuVisible = show)"
    >
      <div class="menu-content" style="padding-top: 0px" @click="contextMenuVisible=false">
        <el-row>
          <div class="menu-item" v-if="menu.open" @click="openFolder(menu.folder)">打开</div>
        </el-row>
        <el-row>
          <div class="menu-item" v-if="menu.newFolder" @click="menuNewFolder">新建文件夹</div>
        </el-row>
        <el-row>
          <div class="menu-item" v-if="menu.download" @click="menuDownload" >下载</div>
        </el-row>
        <el-row>
          <div class="menu-item" v-if="menu.upload"  >上传文件</div>
        </el-row>

        <el-row>
          <div class="menu-item" v-if="menu.newFolder" @click="getData">刷新</div>
        </el-row>

        <el-row>
          <div class="menu-item" v-if="menu.share" @click="menuShare">分享</div>
        </el-row>
        <el-row>
          <div class="menu-item" v-if="menu.preview" @click="menuPreview">查看</div>
        </el-row>
        <el-row>
          <div class="menu-item" v-if="menu.collection">收藏</div>
        </el-row>
        <el-row style="height: 12px" v-if="menu.isItem">
          <hr />
        </el-row>

        <el-row v-if="menu.isItem">
          <div  class="menu-item" @click="menuReName">重命名</div>
        </el-row>

        <el-row v-if="menu.isItem">
          <div  class="menu-item">移到文件</div>
        </el-row>
        <el-row v-if="menu.isFile">
          <div  class="menu-item" @click="menuSafe">移到保险箱</div>
        </el-row>
        <el-row v-if="menu.isItem">
          <div  class="menu-item" @click="menuDetail">查看详细信息</div>
        </el-row>
        <el-row style="height: 12px" v-if="menu.isItem">
          <hr />
        </el-row>
        <el-row v-if="menu.isItem">
          <div  class="menu-item menu-item-delete" @click="menuDelete">移到回收站</div>
        </el-row>
      </div>
    </context-menu>


    <basic-container >
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item v-for="item in titleFolderCopy" v-bind:key="item.folderId" >
          <a href="javascript:void(0);" @click="folderBack(item.folderId)">{{item.folderName}}</a>
        </el-breadcrumb-item>
      </el-breadcrumb>
      <el-row style="position: absolute;right: 20px;top: 20px;">
        <el-button icon="el-icon-search" circle></el-button>
        <el-button type="primary" icon="el-icon-edit" circle></el-button>
<!--        <el-button type="success" icon="el-icon-check" circle></el-button>-->
        <el-button type="success" icon="el-icon-share" size="medium " circle @click="menuShare"></el-button>
        <el-button type="warning" icon="el-icon-star-off" circle></el-button>
        <el-button type="danger" icon="el-icon-delete" circle></el-button>
      </el-row>
      <div id="files"  @contextmenu="showContextMenu"  @contextmenu.prevent.stop="blankMenu($event)"  >

        <div :class="file.isChecked?'file-item file-item-active':'file-item'" :key="file.id" v-for="file in folderList" @dblclick="openFolder(file)" @contextmenu="showContextMenu"  @contextmenu.prevent.stop="folderMenu($event,file)" >

          <div class="file-item-select">
            <div class="file-item-select-item"><el-checkbox class="file-select" v-model="file.isChecked"  @change="itemChange('folder',file.id)" size="medium" label="" name="type"></el-checkbox></div>
            <div class="file-item-select-item" >...</div>
          </div>

          <div style="height: 100px">
          <svg  class="icon disk-icon" aria-hidden="true">
            <use xlink:href="#icon-folder"></use>
          </svg>
          </div>
          <div class="file-msg">
            <div ><div class="file-name">
              {{file.folderName}}</div></div>
            <div class="file-createTime" v-text="file.createTime"></div>
          </div>

        </div>

        <div :class="file.isChecked?'file-item file-item-active':'file-item'" :key="file.id" v-for="file in fileList" @contextmenu="showContextMenu($event,file)" @contextmenu.prevent.stop="fileMenu($event,file)" >

          <div class="file-item-select">
            <div class="file-item-select-item"><el-checkbox class="file-select" v-model="file.isChecked"  @change="itemChange('file',file.id)" size="medium" label="" name="type"></el-checkbox></div>
            <div class="file-item-select-item" ><el-button type="primary" icon="el-icon-view" circle @click="menuPreview"></el-button></div>
          </div>

          <div style="height: 100px">
            <svg  class="icon disk-icon" aria-hidden="true">
              <use :xlink:href="'#icon-'+ (file.bucketName == 'blank' ? file.fileSuffix :file.fileSuffix)"  ></use>
            </svg>
          </div>


          <div class="file-msg">
            <div class="file-msg-one" ><div class="file-name">
                {{file.fileName}}


            </div></div>
            <div class="file-createTime" v-text="file.createTime"></div>
          </div>
        </div>
      </div>

      <!-- 分享文件对话框     -->
      <el-dialog
        title="文件分享"
        :visible.sync="share"
        width="40%">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="标题名称">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="有效时长">
            <el-select v-model="form.minEffective"  placeholder="请选择有效时长">
              <el-option label="永久"   :value="365*60*24*10"></el-option>
              <el-option label="一天" :value="60*24"></el-option>
              <el-option label="两天" :value="2*60*24"></el-option>
              <el-option label="三天" :value="3*60*24"></el-option>
              <el-option label="四天" :value="4*60*24"></el-option>
              <el-option label="五天" :value="5*60*24"></el-option>
              <el-option label="七天" :value="7*60*24"></el-option>
              <el-option label="十五天" :value="15*60*24"></el-option>
              <el-option label="一个月" :value="30*60*24"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  label="路径名称">
            <el-input v-model="form.path" disabled=""></el-input>
          </el-form-item>
          <el-form-item label="是否加密">
            <el-switch v-model="form.hasPwd"   ></el-switch>
          </el-form-item>
          <el-form-item v-if="form.hasPwd" label="设置密码">
            <el-input type="password" v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="分享链接">
            <el-link type="primary"  @click="copyMessage('http://localhost/#/share?path='+form.path+'&密码：'+form.password)" target="_blank">http://localhost/#/share?path={{form.path}}</el-link>
          </el-form-item>
          <el-form-item label="文件描述">
            <el-input type="textarea" v-model="form.description"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="share = false">取 消</el-button>
    <el-button type="primary" @click="shareForm">分 享</el-button>
  </span>
      </el-dialog>


    </basic-container>
  </div>
</template>

<script>
  import { diskIndex } from "@/api/disk/index";
  import { saveFolder,moveToRecycleBin } from "@/api/disk/folder";
  import  {fileMoveToRecycleBin,updateFile} from "@/api/disk/file";
  import  {saveShare} from "@/api/disk/share";
  import {mapGetters,mapState} from 'vuex';
  import $ from 'jquery';
  import DiskUtil from "@/util/disk";

  export default {
    name: 'disk',
    data() {
      return {
        form:{
          title:"华软毕业照合集",
          path:"dfds",
          minEffective:"0",
          password:"",
          hasPwd:false
        },
        shareOne:{},
        share: false,
        folder:{
          folderName: "新建文件夹",
          id: '',
          parentId: "",
        },
        titleFolderCopy: [],
        menu:{
          preview:false,
          newFolder:false,
          download:false,
          upload:false,
          share:false,
          collection:false,
          isItem:false,
          isFile:false,
          open:false,
          name:"",
          file:[],
          folder:[]
        },
        contextMenuVisible: false,
        contextMenuOffset: {
          left: 0,
          top: 0
        },
        folderList:[],
        fileList: [{
          createTime:""
        }]
      }
    },
    transitions(){
      console.log("transitions")
    },
    created(){

      this.searchData.folderId="1";
      this.init();
    },
    mounted() {


      var that = this;
      DiskUtil.$on('refreshDisk', function (param) {
        console.log(param);
        that.getData();
      })

    },
    computed: {
      ...mapGetters(["preview","titleFolder","searchData","repository"]),
    },
    methods: {
      copyMessage(msg) {
        var _this = this;
        this.$copyText(msg).then(function (e) {
          _this.$message.success("复制成功,快去分享给你的好友吧!")
        }, function (e) {
          _this.$message.error('Can not copy')
        })
      },
      shareForm(){
        if (!this.form.hasPwd){
          this.form.password = '';
        }
        saveShare(this.form).then(re=>{
          console.log(re.data)
          if (re.data.code == 0){
            this.$message.success(re.data.msg);
          }else{
            this.$.message.error(re.data.msg);
          }

        }).catch(()=>{
          this.$message.error("分享失败,请稍后再试")
        })
      },
      defaultMenu(){
        this.menu.preview=false;
          this.menu.newFolder=false;
          this.menu.download=false;
          this.menu.upload=false;
          this.menu.share=false;
          this.menu.collection=false;
          this.menu.isItem=false;
          this.menu.open=false;
          this.menu.isFile=false;

      },
      init(){
        this.getData();
        this.titleFolderCopy = this.titleFolder;
      },
      getData() {
        this.tableLoading = true;
        console.log("=====searchData=======");
        console.log(this.searchData);
        diskIndex(this.searchData)
          .then(data => {
            console.log(data.data.data);
            console.log(data.data.data.folderList);
            this.fileList = data.data.data.fileList;
            this.folderList = data.data.data.folderList;
            // this.repository = data.data.data.repository;
            this.$store.commit('SET_REPOSITORY',data.data.data.repository);
            console.log("this.repository")
            console.log(this.repository)
          })
          .catch(() => {
            loading();
          });


      },
      openFile(file){

        console.log("file")
      },
      openFolder(folder) {
        const folderId = folder.id;
        const folderName = folder.folderName;
        this.titleFolderCopy.push({folderId:folderId,folderName:folderName});
        this.searchData.folderId=folderId;
        this.searchData.folderName=folderName;
        this.getData();
      },
      blankMenu(e){
        e.preventDefault();
        this.defaultMenu();
        this.menu.name="新建文件夹";
        this.menu.newFolder = true;
        this.menu.upload = true;
        this.menu.name="新建文件夹";
        this.menu.canNewFolder=true;
      },
      fileMenu(e,file){
        e.preventDefault();
        this.defaultMenu();
        this.menu.isFile=true;
        this.menu.isItem=true;
        this.menu.download=true;
        this.menu.share=true;
        this.menu.preview=false;
        this.menu.file=file;
        console.log(file)
        let Base64 = require('js-base64').Base64
        if (file != null && file != undefined){
          this.preview.title=file.fileName;
          this.preview.url='http://127.0.0.1:8012/onlinePreview?url='
            +encodeURIComponent(Base64.encode("http://localhost:9000/"+file.bucketName+"/"+file.filePath));
          this.menu.preview=true;
        }


      },
      folderMenu(e,folder){
        e.preventDefault();
        this.defaultMenu();
        this.menu.isItem=true;
        this.menu.open=true;
        this.menu.share=true;
        // this.menu.
        this.menu.folder=folder;

      },
      menuOpenFolder(){

      },
      menuNewFolder(){
        this.$prompt('', '新建文件夹', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: "新建文件夹",
          inputPlaceholder:"请输入文件夹名称",
          // message:"dfdfd",
          // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          // inputErrorMessage: '邮箱格式不正确'
        }).then(({ value }) => {
          this.folder.folderName = value;
          this.folder.parentId = this.searchData.folderId;
          //新建文件夹
          saveFolder(this.folder)
            .then(data => {
              console.log(data.data)
              if (data.data.code == 0){
                this.$message({
                  type: 'success',
                  message: '新建文件夹成功: ' + value
                });
                this.getData();
              }else {
                this.$message({
                  type: 'success',
                  message: data.data.msg
                });
              }
            })
            .catch(() => {
              this.$notify({
                message: '新建文件夹失败!',
                type: 'error'
              });
            });


        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },
      menuDownload(){
        location.href="http://localhost:9000/"+this.menu.file.bucketName+"/"+this.menu.file.filePath;
        this.$notify({
          title: '文件开始下载',
          message: ''+this.menu.file.fileName,
          type: 'success'
        });

      },
      menuUpload(){

      },
      menuShare(){
        var fileIds = "";
        var folderIds = "";
        var name = '';

        this.fileList.forEach(file => {
          if (file.isChecked){
            fileIds += file.id + ","
            name += file.fileName;
          }
        });
        this.folderList.forEach(file => {
          if (file.isChecked){
            folderIds += file.id + ","
            name += file.folderName;
          }
        });
        if (fileIds != '' && folderIds != ''){
          //多文件分享
          this.share = true;
          this.form.path = new Date().getTime();
          this.form.fileIds = fileIds;
          this.form.folderIds = folderIds;
          if (name.length > 20){
            this.form.title = name.substring(0,20)+"...等文件";
          }else{
            this.form.title = name;
          }



        }else{
          //单文件分享
          this.share = true;
          this.form.path = new Date().getTime();
          if (this.menu.isFile){
            this.form.fileIds=this.menu.file.id;
            this.form.title = this.menu.file.fileName
          }else{
            this.form.folderIds = this.menu.folder.id;
            this.form.title = this.menu.folder.folderName;
          }
        }



      },
      menuPreview(){
        this.preview.state=true;
        this.$store.commit('SET_PREVIEW',this.preview);
      },
      menuCollection(){

      },
      menuReName(){
        this.$prompt('', '文件(夹)重命名', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: this.menu.isFile?this.menu.file.fileName:this.menu.folder.folderName,
          // message:"dfdfd",
          // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          // inputErrorMessage: '邮箱格式不正确'
        }).then(({ value }) => {
          this.$message({
            type: 'success',
            message: '重命名成功: ' + value
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });

      },
      menuRefresh(){

      },
      menuMove(){

      },
      menuSafe(){
        this.$confirm('此操作该文件将移动到保险柜, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {

          this.menu.file.delFlag = '2';
          updateFile(this.menu.file).then(re=>{
            if (re.data.code == 0)
              this.$message({
                type: 'success',
                message: '成功移动到保险柜!'
              });
            this.getData();
          });


        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      menuDetail(){

        this.$alert('<div>' +

          '<div style="width: 100%;align-content: center;align-items: center;text-align: center;">' +
          '<svg style="width: 90px;height: 90px;position: relative;top: 0;' +
          '            bottom: 0;' +
          '            left: 0;' +
          '            right: 0;' +
          '            margin: auto;" class="icon disk-icon" aria-hidden="true">\n' +
          ' <use xlink:href="#icon-'+ (this.menu.file.bucketName == 'blank' ? this.menu.file.fileSuffix :this.menu.file.fileSuffix)+'" ></use>' +
          '            </svg>' +
          '</div>' +
          '<div><strong>详细信息：</strong></div><div><a :href="000" >'+this.menu.file.fileName+'</a></div><div>'+this.menu.file.fileSize+'KB</div></br>' +
          '<div><strong>文件位置：</strong></div><div>'+this.menu.file.folderIds+'</div></br>' +
          '<div><strong>创建时间：</strong></div><div>'+this.menu.file.createTime+'</div></br>' +
          '<div><strong>修改时间：</strong></div><div>'+this.menu.file.changeTime+'</div></br>' +
          '</div>', this.menu.file.fileName, {
          dangerouslyUseHTMLString: true,
          showConfirmButton:false
        });

      },
      menuDelete(){
        this.$confirm('将该文件(夹)移到回收站, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          if (this.menu.isFile) {
            //文件删除
            fileMoveToRecycleBin(this.menu.file.id)
              .then(data => {
                console.log(data.data.data);
                this.$message({
                  type: 'success',
                  message: '文件删除成功!'
                });
                this.getData()
              })
              .catch(() => {
                this.$message({
                  type: 'error',
                  message: '文件删除失败!'
                });
              });

          }else {
            //文件夹删除
            moveToRecycleBin(this.menu.folder.id)
              .then(data => {
                console.log(data.data.data);
                this.$message({
                  type: 'success',
                  message: '文件夹删除成功!'
                });
                this.getData()
              })
              .catch(() => {
                this.$message({
                  type: 'error',
                  message: '文件夹删除失败!'
                });
              });
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      folderBack(folderId){
        if (folderId == this.searchData.folderId){
          return;
        }
        if (folderId == "1" || folderId== ""){
          this.titleFolderCopy=[{folderId:"",folderName:"文件"}];
          // this.titleFolder.push({folderId:"",folderName:"文件"});
        }else{
          var item = new Array();

          for (let i = 0; i < this.titleFolder.length; i++) {
            if (folderId == this.titleFolder[i].folderId){
              this.titleFolderCopy.splice(0,i);
            }
          }
        }
        this.searchData.folderId=folderId;
        this.getData();
      },
      showContextMenu(e,file) {


        e.preventDefault();
        this.contextMenuVisible = true;
        this.contextMenuOffset = {
          left: e.pageX,
          top: e.pageY
        };
      },
      changeMenu(e,file){
        e.preventDefault();
        console.log("file");
        this.menu.name=file.folderName;
        this.menu.canNewFolder = false;
      },
      changeMenuOfFile(e,file){
        e.preventDefault();
        console.log("file");
        this.menu.name=file.fileName;
        this.menu.canNewFolder = false;
      },
      itemChange(type,id){


        if (type == 'file'){
          this.fileList.forEach(file => {
            if (file.id == id){
              console.log(file.isChecked)
              this.$set(file ,  'isChecked',  file.isChecked);
              return true;
            }
          })
        }else{
          this.folderList.forEach(file => {
            if (file.id == id){
              this.$set(file ,  'isChecked',  file.isChecked);
              return true;
            }
          })

        }
        console.log(this.fileList)

      }
    }
  }
</script>

<style scoped="scoped" lang="scss">

//右键样式
.menu-content{
  padding: 5px;
  width: 150px;
  border-radius: 10px;
  background-color: #ffffff;
  border: 1px #b1b1b1 solid;
  box-shadow: 5px 5px 5px #b1b1b1;
  .menu-item{
    cursor: pointer;
    padding: 5px;
    text-align: left;
    margin-top: 5px;
    width: 100%;
    border-radius: 5px;
    &:hover{
      background-color: #2d8cf0;
      color: #ffffff;
    }

  }
  .menu-item-delete{
    color: red;
    &:hover{
      background-color: red;
      color: #ffffff;
    }
  }

}


.context-menu {
  .ctx-menu {
    min-width: 65px;
    font-size: 14px;

    li {
      padding: 5px 14px;
      text-align: center;
      cursor: pointer;

      &:hover {
        background-color: #409eff;
      }
    }
  }
}

.icon {
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
.disk-icon{
  //background-color: #19be6b;
  height: 120px!important;
  width: 100px!important;
}
#files{
  min-height: 200px;
}
.file-item{

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  align-content: center;
  float: left;
  width: 150px;
  margin: 10px;
  //background-color: #ed3f14;
  height: 180px;
  border-radius: 10px;

}
.file-item:hover{
  opacity: 0.9;
  background-color: #c8c9cb;
}
.file-item-active{
  opacity: 0.9;
  background-color: #c8c9cb;
}

.file-item-select-item{
  width: 20px;
  display: none;
}
.file-item:hover .file-item-select-item{
  display: block;
}
.file-select:checked{
  display: block;
}
.file-item-select{
  //height: 30px;
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-self: flex-start;
}
.file-msg{
  font-weight: bold;
  margin-top: 20px;
  width: 100%;
  height: 50px;
  //background-color: #2d8cf0;
}
.file-name{

  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  text-align: center;
  //font-size: 20px;
}
.file-createTime{

  margin-top: 10px;
  font-size: 13px;
  text-align: center;
}
</style>
